<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/12
 * Time: 18:18
 */

namespace Application\Controllers;


use Application\Models\BookCategory;
use Application\Models\BookKanCloud;
use Phalcon\Mvc\Controller;

class BookController extends Controller
{
    private $soncat = [];

    public function indexAction()
    {
        $this->view->setVar('list', BookCategory::find());
    }


    //获取所有下级  不算分类本身
    private function getsoncat($cid)
    {
        $list = BookCategory::find(['pid=?0', 'bind' => [$cid]])->toArray();
        $this->soncat[] = $cid;
        foreach ($list as $value) {
            $this->getsoncat($value['id']);
        }
    }

    public function categoryAction()
    {
        $id = $this->request->get('id', null, 0);
        $firstArticle = BookKanCloud::findFirst([
            'conditions'=>'cid = '.$id,
            'columns'=>'id,cid,title'
        ]);
        $this->view->setVar('fristUrl', $this->url->get('/book/info', ['id' => $firstArticle->id]));
        $this->view->setVar('catinfo', BookCategory::findFirst($id));
    }

    public function articlesAction()
    {
        $id = $this->request->get('id', null, 0);
        $this->getsoncat($id);
        if (!$this->soncat) {
            die("Whoops");
        }
        $catlist = BookKanCloud::find([
            'cid in ({cid:array})',
            'bind' => [
                'cid' => $this->soncat
            ],
            'order' => 'cid desc'
        ])->toArray();
        $tmp = [];
        foreach ($catlist as $key => $value) {
            $a = array(
                'id' => $value['id'],
                'text' => $value['title'],
                'children' => false,
            );
            $tmp[] = $a;
        }
        return $this->response->setJsonContent($tmp);
    }


    public function infoAction()
    {
        $id = $this->request->get('id', null, 0);
        if (!$id) {
            return false;
        }
        $info = BookKanCloud::findFirst($id);
        $catid = $info->cid;
        $next = BookKanCloud::findFirst([
            "id > ".$id.' and cid='.$catid,
            "order"=>"id desc"
        ]);
        if (!$info) {
            return $this->response->setContent('没有文档');
        }
        $prev = BookKanCloud::findFirst([
            "id > ".$id.' and cid='.$catid,
            "order"=>"id desc"
        ]);
        $this->view->setVar('next',$next->id ? $this->url->get('/book/info',['id'=>$next->id]) : '');
        $this->view->setVar('prev',$prev->id? $this->url->get('/book/info',['id'=>$prev->id]) : '');
        $this->view->setVar('info',$info);
    }
}